#pragma once

#include <string>
#include <iostream>
#include <stdarg.h>
#include <unistd.h>
#include <ctime>
#include <fstream>

#define LOG_NORMAL "log.txt"
#define LOG_ERR "log.error"

// 日志等级
#define DEBUG 0
#define NORMAL 1
#define WARNING 2
#define ERROR 3
#define FATAL 4

#define NUM 1024

const char *to_levelstr(int level)
{
    switch (level)
    {
    case DEBUG:
        return "DEBUG";
    case NORMAL:
        return "NORMAL";
    case WARNING:
        return "WARNING";
    case ERROR:
        return "ERROR";
    case FATAL:
        return "FATAL";
    default:
        return nullptr;
    }
}

void logMessage(int level, const char *format, ...)
{
    //[日志等级] [时间] [pid] [错误信息]

    time_t curTime = time(nullptr);
    struct tm *s_tm = localtime(&curTime);

    char logprefix[NUM];
    snprintf(logprefix, sizeof(logprefix), "[%s][%d/%d/%d-%d:%d:%d][pid: %d]",
             to_levelstr(level),
             s_tm->tm_year + 1900, s_tm->tm_mon + 1, s_tm->tm_mday, s_tm->tm_hour, s_tm->tm_min, s_tm->tm_sec,
             getpid());

    char logcontent[NUM];
    va_list arg;
    va_start(arg, format);
    vsnprintf(logcontent, sizeof(logcontent), format, arg);

    std::cout << logprefix << logcontent << std::endl;

    // std::string log = logprefix;
    // log += logcontent;

    // std::string f;
    // if(level==DEBUG || level==NORMAL || level==WARNING ) f=LOG_NORMAL;
    // if(level==ERROR || level==FATAL) f=LOG_ERR;
    // //以追加的方式打开，重新启动时会保留上一次启动的log，可以在initServer中默认启动一次，即启动时先清空，就只保留本次的了
    // std::ofstream ofs(f, std::ios::app);                                              
    // ofs.write(log.c_str(), log.size());
    // ofs.write("\n",1);
    // ofs.close();
}